package org.linkerproject.browser;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent; 
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.imlinker.util.StringUtils;

public class UrlDialog extends Dialog {

	private Text text;
	protected Object result;
	protected Shell shell;

	/**
	 * Create the dialog
	 * 
	 * @param parent
	 * @param style
	 */
	public UrlDialog(Shell parent, int style) {
		super(parent, style);
	}

	/**
	 * Create the dialog
	 * 
	 * @param parent
	 */
	public UrlDialog(Shell parent) {
		this(parent, SWT.NONE);
	}

	public UrlDialog(Shell parent, BrowserManager manager) {
		this(parent);

		this.manager = manager;
	}

	/**
	 * Open the dialog
	 * 
	 * @return the result
	 */
	public Object open() {
		createContents();
		initListener();
		text.forceFocus();
		shell.open();
		shell.layout();
		Display display = getParent().getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}

		return result;
	}

	private void initListener() {
		cancelButton.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseUp(MouseEvent e) {
				shell.dispose();
			}

		});

		text.addKeyListener(new KeyAdapter() {

			@Override
			public void keyReleased(KeyEvent e) {
				if (e.keyCode == 13) {
					String url = text.getText();
					if (StringUtils.isNotEmpty(url)) {
						manager.browse(url);
					}
					shell.dispose();
				}
			}
		});

		okButton.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseDown(MouseEvent e) {
				String url = text.getText();
				if (StringUtils.isNotEmpty(url)) {
					manager.browse(url);
				}
			}

			@Override
			public void mouseUp(MouseEvent e) {
				shell.dispose();
			}

		});
	}

	/**
	 * Create contents of the dialog
	 */
	protected void createContents() {
		shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
		shell.setSize(500, 109);
		shell.setText("Url dislog");

		okButton = new Button(shell, SWT.NONE);
		okButton.setText("OK");
		okButton.setBounds(434, 47, 48, 25);

		text = new Text(shell, SWT.BORDER);
		text.setTextLimit(200);
		text.setBounds(66, 10, 416, 25);

		final Label urlLabel = new Label(shell, SWT.NONE);
		urlLabel.setText("Url");
		urlLabel.setBounds(30, 22, 30, 13);

		cancelButton = new Button(shell, SWT.NONE);
		cancelButton.setText("Cancel");
		cancelButton.setBounds(375, 47, 48, 25);
		//
	}

	private Button okButton;
	
	private Button cancelButton;

	private BrowserManager manager;

}
